import os
import requests  # 用于发送HTTP请求到云服务器
import time
from functools import wraps

from flask import render_template, url_for, flash, redirect, session, request, send_from_directory
from werkzeug.utils import secure_filename

from DHsystem import app, db
from DHsystem.forms import RegistrationForm, LoginForm
from DHsystem.models import User
from werkzeug.security import generate_password_hash, check_password_hash
from DHsystem.algorithms.DCP import process_image as dcp_process
from DHsystem.algorithms.fastDCP import process_image as fastdcp_process
from DHsystem.algorithms.AODnet.dehaze import process_image as aodnet_process
from DHsystem.algorithms.DehazeNet.pre_trans import process_image as dehazenet_process

from DHsystem.algorithms.Dehazeformer.test import process_image as dehazeformer_process

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:  # 检查会话中是否存在用户ID
            flash('请先登录！', 'warning')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data)
        user = User(username=form.username.data, password=hashed_password, email=form.email.data)
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created! You can now log in.', 'success')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and check_password_hash(user.password, form.password.data):
            session['user_id'] = user.id  # 将用户ID存入会话
            session['username'] = user.username  # 将用户名存入会话
            flash('Login successful!', 'success')
            return redirect(url_for('process'))  # 登录成功后跳转到功能页面
        else:
            flash('Login unsuccessful. Please check username and password.', 'danger')
    return render_template('login.html', form=form)


@app.route('/process', methods=['GET', 'POST'])
@login_required  # 确保用户已登录
def process():
    if request.method == 'POST':
        # 检查是否有文件被上传
        if 'file' not in request.files:
            flash('没有文件被上传', 'danger')
            return redirect(request.url)

        file = request.files['file']

        # 检查文件是否为空
        if file.filename == '':
            flash('没有选择文件', 'danger')
            return redirect(request.url)

        # 检查文件是否是允许的类型
        if file and allowed_file(file.filename):
            # 保存文件到 uploads 文件夹
            filename = secure_filename(file.filename)
            upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(upload_path)

            # 获取用户选择的算法
            algorithm = request.form.get('algorithm', 'DCP')

            # 根据算法选择处理函数
            if algorithm == 'DCP':
                processed_filename = dcp_process(upload_path, app.config['UPLOAD_FOLDER'])
            elif algorithm == 'fastDCP':
                processed_filename = fastdcp_process(upload_path, app.config['UPLOAD_FOLDER'])
            elif algorithm == 'AODnet':
                processed_filename = aodnet_process(upload_path, app.config['UPLOAD_FOLDER'])
            elif algorithm == 'Dehazeformer':
                processed_filename = dehazeformer_process(upload_path, app.config['UPLOAD_FOLDER'])
            elif algorithm == 'DehazeNet':
                processed_filename = dehazenet_process(upload_path, app.config['UPLOAD_FOLDER'])

            else:
                flash('无效的算法选择', 'danger')
                return redirect(request.url)

            return render_template(
                'process.html',
                original_image=url_for('uploaded_file', filename=filename),
                processed_image=url_for('uploaded_file', filename=processed_filename),
                algorithm=algorithm  # 传递算法名称到前端
            )

    return render_template('process.html')


# 配置上传文件夹和允许的文件类型
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

# 用于显示上传文件的路由
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

# 注销路由
@app.route('/logout')
def logout():
    session.clear()  # 清除会话
    flash('您已成功注销。', 'info')
    return redirect(url_for('login'))